//
//  UserDataManager.m
//  HYSmileiOS
//
//  Created by alekye on 16/5/31.
//  Copyright © 2016年 heyou. All rights reserved.
//

#import "UserDataManager.h"
#import "heyou.h"

#define K_LOCAL_USER_DATA  @"K_LOCAL_USER_DATA"
#define K_LOCAL_USER_DATA_WEIBO  @"K_LOCAL_USER_DATA_WEIBO"

@implementation UserDataManager

/**
 *  数据管理
 *
 *  @return 单实例
 */
+ (instancetype)sharedInstance {
    static UserDataManager *dataInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dataInstance = [[self alloc] init];
    });
    return dataInstance;
}

#pragma mark -- Local User Data

/**
 *  保存当前用户信息
 *
 *  @param userData 用户信息，如果为nil时，删除本地用户信息
 */
- (void)saveUserDataToLocal:(UserInfoDetail*)userData {
    [self _saveDataToLocal:userData forKey:K_LOCAL_USER_DATA];
}

/**
 *  读取本地存储的用户信息
 *
 *  @return 当前用户信息
 */
- (UserInfoDetail*)readUserDataFromLocal {
    UserInfoDetail *userData = nil;
    
    userData = [self _readDataFromLocal:[UserInfoDetail class] forKey:K_LOCAL_USER_DATA];
    
    return userData;
}

/**
 *  保存数据
 *
 *  @param obj 对象
 *  @param key key
 */
- (void)_saveDataToLocal:(NSObject*)obj forKey:(NSString*)key {
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    if (obj == nil) {
        [userDefault removeObjectForKey:key];
    } else {
        NSMutableDictionary *dic = [obj mj_keyValues];
        [userDefault setObject:dic forKey:key];
    }
    
}

/**
 *  读取对象
 *
 *  @param clazz 类型
 *  @param key   key
 *
 *  @return 对象
 */
- (id)_readDataFromLocal:(Class)clazz forKey:(NSString*)key {
    id data = nil;
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *dic = [userDefault objectForKey:key];
    if (dic && [dic isKindOfClass:[NSDictionary class]]) {
        data = [clazz mj_objectWithKeyValues:dic];
    }
    
    return data;
}

@end
